package com.comm.utils;

import com.comm.module.bean.ApiException;
import com.comm.module.bean.HttpResult;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/10/8.
 */

public class TransformUtils {

    public static <T> Observable.Transformer<T, T> defaultSchedulers() {
        return new Observable.Transformer<T, T>() {
            @Override
            public Observable<T> call(Observable<T> tObservable) {
                return tObservable.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io());
            }
        };
    }

    public static <T> Observable.Transformer<HttpResult<T>, T> httpSchedulers() {
        return new Observable.Transformer<HttpResult<T>, T>() {

            @Override
            public Observable<T> call(Observable<HttpResult<T>> httpResultObservable) {
                return httpResultObservable.subscribeOn(Schedulers.io())
                        .flatMap(new Func1<HttpResult<T>, Observable<T>>() {
                            @Override
                            public Observable<T> call(HttpResult<T> tHttpResult) {
                                if (tHttpResult.code == 0) {
                                    return createData(tHttpResult.data);
                                } else {
                                    return Observable.error(new ApiException());
                                }
                            }
                        });
            }
        };
    }

    /**
     * 创建成功的数据
     *
     * @param data
     * @param <T>
     * @return
     */
    private static <T> Observable<T> createData(final T data) {
        return Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                try {
                    subscriber.onNext(data);
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        });
    }
}
